package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"syudy/Models"
)

type RoleController struct {
	BaseController
}

// 角色页面
func (con RoleController) Index(c *gin.Context) {
	rolelist := []Models.Role{}
	Models.DB.Find(&rolelist)
	c.HTML(http.StatusOK, "admin/role/index.html", gin.H{
		"rolelist": rolelist,
	})
}

func (con RoleController) Add(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/role/add.html", gin.H{})
}

// 增加角色
func (con RoleController) DoAdd(c *gin.Context) {
	//strings.Trim去掉空格
	title := strings.Trim(c.PostForm("title"), "")
	description := strings.Trim(c.PostForm("description"), "")
	if title == "" {
		con.Error(c, "角色的标题不能为空", "/admin/role/add")
	} else {
		role := Models.Role{}
		role.Title = title
		role.Description = description
		role.AddTime = con.GetTime()
		err := Models.DB.Create(&role).Error
		if err != nil {
			con.Error(c, "增加角色失败，请重试", "/admin/role/add")
		} else {
			con.Success(c, "增加角色成功", "/admin/role")
		}
	}
}

// 编辑角色
func (con RoleController) Edit(c *gin.Context) {
	id, err := con.StringInt(c.Query("id"))
	if err != nil {
		con.Error(c, "数据传入错误", "/admin/role")
	} else {
		role := Models.Role{Id: id}
		Models.DB.Find(&role)
		c.HTML(http.StatusOK, "admin/role/edit.html", gin.H{
			"role": role,
		})
	}
}

// 执行编辑
func (con RoleController) DoEdit(c *gin.Context) {
	id, err1 := con.StringInt(c.Query("id"))
	if err1 != nil {
		con.Error(c, "传入数据错误", "/admin/role")
	}
	title := strings.Trim(c.PostForm("title"), "")
	description := strings.Trim(c.PostForm("description"), "")
	if title == "" {
		con.Error(c, "传入数据错误", "admin/role")
	} else {
		role := Models.Role{Id: id}
		Models.DB.Find(&role)
		role.Title = title
		role.Description = description
		err := Models.DB.Save(&role).Error
		if err != nil {
			con.Error(c, "修改数据失败", "/admin/role/edit?id="+con.IntString(id))
		} else {
			con.Success(c, "修改数据成功", "/admin/role")
		}
	}
}

// 删除角色
func (con RoleController) Delete(c *gin.Context) {
	id, err := con.StringInt(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
	} else {
		role := Models.Role{Id: id}
		Models.DB.Delete(&role)
		con.Success(c, "删除成功", "/admin/role")
	}
}
